package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.AutoLevelPriceManager;
import com.fish.anne.model.AutoLevelPrice;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class AutoLevelPriceAction extends BaseAction implements Preparable {
    private AutoLevelPriceManager autoLevelPriceManager;
    private List autoLevelPrices;
    private AutoLevelPrice autoLevelPrice;
    private Long  levelPriceId;

    public void setAutoLevelPriceManager(AutoLevelPriceManager autoLevelPriceManager) {
        this.autoLevelPriceManager = autoLevelPriceManager;
    }

    public List getAutoLevelPrices() {
        return autoLevelPrices;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String autoLevelPriceId = getRequest().getParameter("autoLevelPrice.levelPriceId");
            if (autoLevelPriceId != null && !autoLevelPriceId.equals("")) {
                autoLevelPrice = autoLevelPriceManager.get(new Long(autoLevelPriceId));
            }
        }
    }

    public String list() {
        autoLevelPrices = autoLevelPriceManager.getAll();
        return SUCCESS;
    }

    public void setLevelPriceId(Long  levelPriceId) {
        this. levelPriceId =  levelPriceId;
    }

    public AutoLevelPrice getAutoLevelPrice() {
        return autoLevelPrice;
    }

    public void setAutoLevelPrice(AutoLevelPrice autoLevelPrice) {
        this.autoLevelPrice = autoLevelPrice;
    }

    public String delete() {
        autoLevelPriceManager.remove(autoLevelPrice.getLevelPriceId());
        saveMessage(getText("autoLevelPrice.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (levelPriceId != null) {
            autoLevelPrice = autoLevelPriceManager.get(levelPriceId);
        } else {
            autoLevelPrice = new AutoLevelPrice();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (autoLevelPrice.getLevelPriceId() == null);

        autoLevelPriceManager.save(autoLevelPrice);

        String key = (isNew) ? "autoLevelPrice.added" : "autoLevelPrice.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}